package com.orchid.shop.manager.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.orchid.shop.common.exception.MyExceptionHandler;
import com.orchid.shop.manager.mapper.SysUserMapper;
import com.orchid.shop.manager.service.SysUserService;
import com.orchid.shop.model.dto.system.LoginDto;
import com.orchid.shop.model.entity.system.SysUser;
import com.orchid.shop.model.vo.common.ResultCodeEnum;
import com.orchid.shop.model.vo.system.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {

        //获取输入的验证码和存储到redis中的key
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();

        // 格局获取的redis里面的key，查询redis里面存储验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + codeKey);

        //比较输入的验证码和redis存储的验证码是否一致
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsAnyIgnoreCase(captcha, redisCode)){
            throw new MyExceptionHandler(ResultCodeEnum.VALIDATECODE_ERROR);

        }

        // 如果不一样，提示校验失败
        //如果一致，删除redis里面的验证码
        redisTemplate.delete("user:validate" + codeKey);


        //1.获取提交用户名，loginDto获取
        String username = loginDto.getUserName();

        //2.根据用户名查询数据库表 sys_user
        SysUser sysUser = sysUserMapper.selectUserInfoByUsername(username);

        //3.判断用户是否存在
        if(sysUser == null){
//            throw new RuntimeException("用户不存在");
            throw new MyExceptionHandler(ResultCodeEnum.LOGIN_ERROR);
        }

        //4.如果根据用户名查询到用户细信息，用户存在
        //5.获取输入的密码，比较输入的密码和数据库中的密码是否一致
        String database_password = sysUser.getPassword();
        //把输入的密码加密后和数据库中的密码比较 MD5
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if(!input_password.equals(database_password)){
//            throw new RuntimeException("密码错误");
            throw new MyExceptionHandler(ResultCodeEnum.LOGIN_ERROR);
        }

        //6.如果一致，登录成功，如果不一致，登录失败
        //7.登陆成功，生成用户唯一标识
        String token = UUID.randomUUID().toString().replace("-","");

        //8.把登录成功用户信息放到redis里面
        //key:token value:用户信息
        redisTemplate.opsForValue().set("user:login"+token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);

        //9.返回loginvo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    //用户退出
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login" + token);
    }
}
